package com.smilive.start.netty.rpc;

import com.smilive.start.netty.rpc.handle.RpcResponseMessageHandler;
import com.smilive.start.netty.rpc.message.RpcRequestMessage;
import com.smilive.start.netty.rpc.peotocol.RpcMessageCodecSharable;
import com.smilive.start.netty.rpc.peotocol.RpcProtocolFrameDecoder;
import com.smilive.start.netty.rpc.server.RpcHelloServer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: netty
 * @Date: 2022-01-11 10:37
 * @Author: smilive
 * @Description:
 */
@Slf4j
public class RPCClient {

    private static volatile Channel channel = null;
    private static AtomicInteger sequenceId = new AtomicInteger(0);
    private static final Object lock = new Object();
    public static void main(String[] args) {
        //创建代理对象
        // 创建请求并发送
        RpcHelloServer rpcHelloServer = (RpcHelloServer)getProxy(RpcHelloServer.class);
        System.out.println(rpcHelloServer.sayHello("world"));
        System.out.println(rpcHelloServer.sayHello("java"));

    }

    public static Object getProxy(Class<?> serviceClass){
        //因为这边是web程序,那么应该在创建动态代理时使用 Web 应用程序类加载器
        //ClassLoader classLoader = serviceClass.getClass().getClassLoader();//错误的
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        Class<?>[] classes = new Class<?>[]{serviceClass};
        //JDK动态代理
        Object o = Proxy.newProxyInstance(systemClassLoader, classes, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 创建请求并发送
                RpcRequestMessage message = new RpcRequestMessage(sequenceId.getAndIncrement(),
                        serviceClass.getName(),
                        method.getName(),
                        method.getReturnType(),
                        method.getParameterTypes(),
                        args);
                getChannel().writeAndFlush(message).addListener(future -> {
                    if (!future.isSuccess()){
                        log.error(future.cause().toString());
                    }
                });
                //创建Promise，用于获取NIO线程中的返回结果，获取的过程是异步的
                DefaultPromise<Object> promise = new DefaultPromise<>(getChannel().eventLoop());
                RpcResponseMessageHandler.promiseMap.put(message.getSequenceId(),promise);
                // 等待被放入Promise中结果
                promise.await();
                if (promise.isSuccess()) {
                    // 调用方法成功，返回方法执行结果
                    return promise.getNow();
                } else {
                    // 调用方法失败，抛出异常
                    throw new RuntimeException(promise.cause());
                }
            }
        });
        return o;
    }

    //单例模式
    public static Channel getChannel(){
        if (channel != null){
            return channel;
        }
        synchronized (lock){
            if (channel == null){
                ininChannel();
            }
        }
        return channel;
    }

    private static void ininChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        RpcMessageCodecSharable messageSharableCodec = new RpcMessageCodecSharable();
        // PRC 请求消息处理器
        RpcResponseMessageHandler rpcResponseMessageHandler = new RpcResponseMessageHandler();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(group);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new RpcProtocolFrameDecoder());
                ch.pipeline().addLast(loggingHandler);
                ch.pipeline().addLast(messageSharableCodec);
                ch.pipeline().addLast(rpcResponseMessageHandler);
            }
        });
        try {
            channel = bootstrap.connect(new InetSocketAddress( 8000)).sync().channel();
            channel.closeFuture().addListener(future -> {
                group.shutdownGracefully();
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
